import request from "@/api/index";
interface dataSourceType {
  [propName: string]: any;
}
export const checkCreatSiteForm = async (
  _rule: dataSourceType = {},
  value: any
) => {
  if (_rule.required) {
    // 必填项验证非空并排除非必须项
    if ((!value && value !== 0 && value !== false)) {
      return Promise.reject(`${_rule.msg1}`);
    }
    if (value instanceof Array) {
      if (value.length == 0) {
        return Promise.reject(`${_rule.msg1}`);
      }
    }

  }
  if (_rule.api && value) {

    // 没填值没有校验的必要
    var params = detectKey(_rule.key, _rule, value);
    params.id = _rule.id;
    let res = await request[`${_rule.api}`](params);
    if (!res) {
      return Promise.reject(`${_rule.msg2}`);
    } else {
      return Promise.resolve();
    }
  }
};
// 英文数字
export const enNum = async (_rule: dataSourceType, value: string, callback: () => {}, type = 'enNum', msg = '仅支持输入数字、字母', useValue: number = 0) => {

  if (_rule.required) {// 必填项验证非空并排除非必须项
    if (!useValue) { // 使用fullField校验
      if ((value === '' || value === null || value === undefined)) {
        return Promise.reject(`此项必填`);
      } else {
        const reg = /^[A-Za-z0-9]+$/;
        return reg.test(value) ? Promise.resolve() : msg ? Promise.reject(`${msg}`) : Promise.reject(`${_rule.msg}`);
      }
    } else {
      if (!value || value == undefined) {
        return Promise.reject(`${_rule.msg1}`);
      } else {
        const reg = /^[A-Za-z0-9]+$/;
        if (reg.test(value)) {
          if (_rule.api && value) {

            // 没填值没有校验的必要
            var params = detectKey(_rule.key, _rule, value);
            params.id = _rule.id;
            let res = await request[`${_rule.api}`](params);
            if (!res) {
              return Promise.reject(`${_rule.msg2}`);
            } else {
              return Promise.resolve();
            }
          }
        } else {
          return Promise.reject(`${_rule.msg}`);
        }

      }
    }
  }

};
export const detectKey = (
  key: string,
  obj: dataSourceType = {},
  value: any
) => {
  // 要检测的key:value
  let params: dataSourceType = {};
  params[key] = value;
  if (key == "siteDomain" || key == "siteDomainAlias") {
    params["siteProtocol"] = obj.params["siteProtocol"];
  }
  return params;
};
